package com.fenghongzhang.day009;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class DownActivity extends AppCompatActivity {

    private Button down;
    private Button set;
    private ImageView img;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_down);


        down = (Button) findViewById(R.id.down);
        set = (Button) findViewById(R.id.set);
        img = (ImageView) findViewById(R.id.img);


        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            requestPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_EXTERNAL_STORAGE},100);
        }

        set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //
                if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//是否挂载
                    File file = Environment.getExternalStorageDirectory();
                    try {
                        final FileInputStream fileInputStream = new FileInputStream(new File(file, "daxia.jpg"));

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                img.setImageBitmap(BitmapFactory.decodeStream(fileInputStream));
                            }
                        });


//                        File file1 = new File(file, "daxia.jpg");
                        ///storage/emulated/0/daxia.jpg
//                        img.setImageBitmap(BitmapFactory.decodeFile(file1.getAbsolutePath()));

                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
            }
        });


        down.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //开启异步
                new MyTask().execute("http://www.qubaobei.com/ios/cf/uploadfile/132/3/2127.jpg");
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode == 100 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
            //yes
        }else{
            //no
            finish();
        }
    }

    class MyTask extends AsyncTask<String,Void, Bitmap>{

        @Override
        protected Bitmap doInBackground(String... strings) {
            FileOutputStream out=null;
            InputStream inputStream=null;//网络连接的输入流
            HttpURLConnection connection=null;//向SD卡写的输出流
            try {
                URL url= new URL(strings[0]);
                connection= (HttpURLConnection) url.openConnection();
                //不要设置
//                connection.setConnectTimeout(5*1000);
//                connection.setReadTimeout(5*1000);
                if (connection.getResponseCode()==200){
                    inputStream = connection.getInputStream();

                    //下载
                    if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {//是否挂载
                        File file = Environment.getExternalStorageDirectory();
                        out = new FileOutputStream(new File(file,"daxia.jpg"));
                        byte[] bytes=new byte[1024];
                        int len=0;
                        while((len=inputStream.read(bytes))!=-1){
                            out.write(bytes,0,len);
                        }
                    }
                }
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                //关流
                if(out!=null){
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(inputStream!=null){
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if(connection!=null){
                    connection.disconnect();
                }
            }
            return null;
        }

        //进度
        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
        }

        //下载完,自动调用
        @Override
        protected void onPostExecute(Bitmap bitmap) {
            super.onPostExecute(bitmap);
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(DownActivity.this, "开始下载", Toast.LENGTH_SHORT).show();
        }
    }
}
